package com.security.customer.filter;

import com.security.customer.access.CustomerDecideManager;
import com.security.customer.metadata.CustomerPermissionMetadataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @Author: TongRui乀
 * @Date: 2020-04-06 14:03
 * @description： 自定义的过滤器和 SpringSecurity 拦截器
 */
//@Component
public class CustomerAccessSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {

    @Autowired
    private CustomerPermissionMetadataSource customerPermissionMetadataSource;


    @Autowired
    public void setAccessDecisionManager(CustomerDecideManager customerDecideManager) {
        super.setAccessDecisionManager(customerDecideManager);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        FilterInvocation fi = new FilterInvocation(request, response, chain);
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try {
            /**
             * 执行下一个拦截器
             */
            fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
        } finally {
            super.afterInvocation(token, null);
        }
    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return this.customerPermissionMetadataSource;
    }
}
